package com.beichen.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@Component
public class PdfToImageConverterUtil{

    // 支持的图片格式
    private static final String[] SUPPORTED_FORMATS = {"png", "jpg", "jpeg"};

    /**
     * 将PDF转换为图片文件
     * @param pdfFile PDF文件
     * @return 转换后的图片文件
     * @throws IOException 转换异常
     */
    public File convertToImage(File pdfFile) throws IOException {
        System.out.println("开始转换PDF: " + pdfFile.getAbsolutePath());

        try (PDDocument document = PDDocument.load(pdfFile)) {
            if (document.getNumberOfPages() == 0) {
                throw new IOException("PDF文件不包含任何页面");
            }

            PDFRenderer renderer = new PDFRenderer(document);
            System.out.println("渲染PDF第一页...");

            // 渲染第一页
            BufferedImage image = renderer.renderImage(0, 1.5f);

            // 创建临时图片文件
            String tempDir = System.getProperty("java.io.tmpdir");
            String fileName = "cert_" + System.currentTimeMillis() + ".png";
            File imageFile = new File(tempDir, fileName);

            System.out.println("保存图片到: " + imageFile.getAbsolutePath());
            ImageIO.write(image, "png", imageFile);

            return imageFile;
        } catch (IOException e) {
            System.err.println("PDF转换失败: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 检查文件是否为PDF
     * @param file 文件对象
     * @return 是否为PDF
     */
        public boolean isPdfFile(File file) {
            if (file == null || !file.exists()) {return false;}
        String name = file.getName().toLowerCase();
        return name.endsWith(".pdf");
    }
}